/*
 * face_detect.cpp
 *
 *  Created on: Mar 23, 2013
 *      Author: lcad
 */
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <vector>

using namespace std;

static CvMemStorage* storage = 0;
static CvHaarClassifierCascade* cascade = 0;
const char* cascade_name = "haarcascade_frontalface_alt.xml";

void
initialize_face_detection()
{
	cascade = (CvHaarClassifierCascade*) cvLoad (cascade_name, 0, 0, 0);

	if (!cascade)
	{
		fprintf(stderr, "ERROR: Could not load classifier cascade\n");
		exit(-1);
	}

	storage = cvCreateMemStorage(0);
}


CvSeq*
detect_faces_from_image(IplImage *img)
{
	double scale = 0.5;
	CvSeq* faces = NULL;

	IplImage *resized_image = cvCreateImage(cvSize(img->width * scale, img->height * scale), img->depth, img->nChannels);
	cvResize(img, resized_image, CV_INTER_CUBIC);

	cvClearMemStorage(storage);

	if (cascade)
	{
		faces = cvHaarDetectObjects(resized_image, cascade, storage,
			1.1, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(40, 40));
	}

	// re-scale the image rectangles to its real position
	for (int i = 0; i < (faces ? faces->total : 0); i++)
	{
		CvRect* r = (CvRect*) cvGetSeqElem(faces, i);

		r->x = r->x / scale;
		r->y = r->y / scale;
		r->width = r->width / scale;
		r->height = r->height / scale;
	}

	cvReleaseImage(&resized_image);
	return faces;
}


void
draw_image_faces(IplImage *img, CvSeq* faces)
{
	int i;
	CvPoint pt1, pt2;

	for (i = 0; i < (faces ? faces->total : 0); i++)
	{
		CvRect* r = (CvRect*) cvGetSeqElem(faces, i);

		pt1.x = r->x;
		pt1.y = r->y;

		pt2.x = (r->x + r->width);
		pt2.y = (r->y + r->height);

		cvRectangle(img, pt1, pt2, CV_RGB(255,0,0), 3, 8, 0);
	}
}

